import { queryUserLoginApi } from '@/service/user';
import jsCookie from 'js-cookie';
import type { Action, Dispatch, Effect, History, Reducer } from 'umi';
interface SubscriptionAPI {
  dispatch: Dispatch;
  history: History;
}
type PayloadAction<P = any> = Action & { payload: P };

export interface CommonState {
  collapse: boolean;
  isShowDetailDialog: boolean;
  isClearForm: boolean;
  ids: string[];
}

interface ChangeCollapseAction extends PayloadAction<{ collapse: boolean }> {}
interface SetDialogAction extends PayloadAction<{ isShowDetailDialog: boolean }> {}
interface SaveIdsAction extends PayloadAction<{ ids: string[] }> {}
interface ClearFormAction extends PayloadAction<{ isClearForm: boolean }> {}

interface CommonModelType {
  namespace: 'common';
  state: CommonState;
  subscriptions: {
    setup: (params: SubscriptionAPI) => void;
  };
  reducers: {
    changeCollapse: Reducer<Partial<CommonState>, ChangeCollapseAction>;
    setShowDetailDialog: Reducer<Partial<CommonState>, SetDialogAction>;
    clearForm: Reducer<Partial<CommonState>, ClearFormAction>;
    saveSelectIds: Reducer<Partial<CommonState>, SaveIdsAction>;
  };
  effects: {
    queryUserLogin: Effect;
  };
}

const CommonModel: CommonModelType = {
  namespace: 'common',
  state: {
    collapse: false, //- 监听侧边栏是否是小屏幕
    isShowDetailDialog: false,
    isClearForm: false,
    ids: [],
  },
  subscriptions: {
    setup({ dispatch, history }) {
      //- 初始化查询用户是否登录，app.start阶段进行执行
      dispatch({ type: 'queryUserLogin', payload: { history } });
    },
  },
  reducers: {
    changeCollapse: (state, { payload }) => ({ ...state, ...payload }),
    setShowDetailDialog: (state, { payload }) => ({ ...state, ...payload }),
    clearForm: (state, { payload }) => ({ ...state, ...payload }),
    saveSelectIds: (state, { payload }) => ({ ...state, ...payload }),
  },
  effects: {
    *queryUserLogin({ payload }, { put, call }) {
      const { history } = payload;
      const pathname = history.location.pathname;

      const AUTH_WHITE_LIST = ['/users/login', '/user/forgetpwd'];
      if (!AUTH_WHITE_LIST.includes(pathname)) {
        if (!jsCookie.get('token')) {
          history.replace('/users/login');
        } else {
          try {
            yield call(queryUserLoginApi);
          } catch (error) {}
        }
      } else {
      }
    },
  },
};

export default CommonModel;
